/*
(c) 2010 - Open Source Business Foundation e. V. (www.osbf.de)
This software is provided under Microsoft Reciprocal License (Ms-RL)
(http://www.microsoft.com/opensource/licenses.mspx#Ms-RL)
All other rights reserved
*/

var MicroFormatDialog = {
  
  MF_TYPES: [ "hCard", "hCalendar", "hReview" ],
  MF_TYPE_NODES: [ "hCards", "hCalendars", "hReviews" ],
  RE_MF_NODE: new RegExp("mfNode\\[([0-9]+)\\]"),
  RE_STRING_RESPONSE: new RegExp("<string[^>]+>([^<]+)</string>", "m"),
  PLUGIN_REMEMBER_URL: "http://127.0.0.1:81/PluginService.asmx/Remember",
  PLUGIN_LOGIN_URL: "http://127.0.0.1:81/PluginService.asmx/Login",
  APP_BROWSE_URL: "http://127.0.0.1:81/Browse.aspx",
  

  onLoad: function() {
    if ("arguments" in window && window.arguments.length > 0) {
      this.browserDocument = window.arguments[0];
    }
    this.microFormats = parseMicroFormats(this.browserDocument);
    this._addMfTreeNodes();
    var mfUrl = document.getElementById("mfUrl");
    if (mfUrl != null) {
      mfUrl.value = this.browserDocument.location.href;
    }
    var mfTreeCaption = document.getElementById("mfTreeCaption");
    if (mfTreeCaption != null) {
      var captionAttributeLabel = document.createAttribute("label");
      captionAttributeLabel.nodeValue = this.microFormats.length + " MicroFormats found";
      mfTreeCaption.setAttributeNode(captionAttributeLabel);
    }
  },

  onStatusIconClick: function(browserDocument) {
    return window.openDialog("chrome://microformats/content/microformatDialog.xul", "mfDialog", "chrome,centerscreen", browserDocument);
  },
  
  onTreeClicked: function(event) {
    var tree = document.getElementById("mfTree");
    var treeBox = tree.boxObject;
    // get the row, col and child element at the point
    var row = { }, col = { }, child = { };
    treeBox.getCellAt(event.clientX, event.clientY, row, col, child);
    var type = tree.view.getCellText(row.value, tree.columns.getColumnAt(2));
    if (type != null) {
      var matchResult = type.match(this.RE_MF_NODE); 
      if (matchResult != null) {
        if (col.value.index == 0) {
          var checkboxValue = tree.view.getCellValue(row.value, col.value);
          if (checkboxValue == "true") {
            tree.view.setCellValue(row.value, col.value, false);
          } else {
            tree.view.setCellValue(row.value, col.value, true);
          }
        } else {
          var mfIndex = matchResult[1];
          if ((mfIndex >= 0) && this.microFormats && (mfIndex < this.microFormats.length)) {
            this._clearMfPropertyTree();
            this._addMfPropertyTreeNodes(this.microFormats[mfIndex]);
          }
        }
      }
    }
  },
  
  onButtonSelectAll: function() {
    var mfTree = document.getElementById("mfTree");
    var mfTreeRows = findElementNodes(mfTree, "treerow");
    for (var i = 0; i < mfTreeRows.length; i++) {
      var mfTreeCells = mfTreeRows[i].childNodes;
      if ((mfTreeCells != null) && (mfTreeCells.length > 2) && (mfTreeCells[2].getAttribute("label") != "mfType")) {
        var attributeValue = document.createAttribute("value");
        attributeValue.nodeValue = "true";
        mfTreeCells[0].setAttributeNode(attributeValue);
      }
    }
  },
  
  onButtonDeselectAll: function() {
    var mfTree = document.getElementById("mfTree");
    var mfTreeRows = findElementNodes(mfTree, "treerow");
    for (var i = 0; i < mfTreeRows.length; i++) {
      var mfTreeCells = mfTreeRows[i].childNodes;
      if ((mfTreeCells != null) && (mfTreeCells.length > 2) && (mfTreeCells[2].getAttribute("label") != "mfType")) {
        var attributeValue = document.createAttribute("value");
        attributeValue.nodeValue = "false";
        mfTreeCells[0].setAttributeNode(attributeValue);
      }
    }
  },
  
  onButtonExpandTree: function() {
    var mfTree = document.getElementById("mfTree");
    var mfTreeItems = findElementNodes(mfTree, "treeitem");
    for (var i = 0; i < mfTreeItems.length; i++) {
      if (mfTreeItems[i].getAttribute("container") == "true") {
        var attributeOpen = document.createAttribute("open");
        attributeOpen.nodeValue = "true";
        mfTreeItems[i].setAttributeNode(attributeOpen);
      }
    }
  },
  
  onButtonCollapseTree: function() {
    this._clearMfPropertyTree();
    var mfTree = document.getElementById("mfTree");
    var mfTreeItems = findElementNodes(mfTree, "treeitem");
    for (var i = 0; i < mfTreeItems.length; i++) {
      if (mfTreeItems[i].getAttribute("container") == "true") {
        var attributeOpen = document.createAttribute("open");
        attributeOpen.nodeValue = "false";
        mfTreeItems[i].setAttributeNode(attributeOpen);
      }
    }
  },
  
  _getMfSession: function() {
    var prefManager = Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefBranch);
    try {
      return prefManager.getCharPref("extensions.microformats.session");
    } catch (e) {
      return null;
    }
  },
  
  _setMfSession: function(mfSession) {
    var prefManager = Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefBranch);
    prefManager.setCharPref("extensions.microformats.session", mfSession);
  },
  
  onButtonRemember: function() {
    var mfSession = this._getMfSession();
    if ((mfSession != null) && (mfSession.length > 0)) {
      this._postMfData(mfSession);
    } else {
      this.loginDialog = window.openDialog("chrome://microformats/content/loginDialog.xul", "mfLoginDialog", "chrome,centerscreen", this);
    }
  },
  
  onButtonBrowse: function() {
    var browseUrl = this.APP_BROWSE_URL;
    var mfSession = this._getMfSession();
    if ((mfSession != null) && (mfSession.length > 0)) {
      browseUrl += "?sessionId=" + mfSession;
    }
    window.opener.gBrowser.selectedTab = window.opener.gBrowser.addTab(browseUrl);
  },
  
  onLogin: function(userId, password) {
    this.loginDialog = null;
    var parameters = "userId=" + userId + "&password=" + password;
    var xmlHttpReq = new XMLHttpRequest();
    xmlHttpReq.open("POST", this.PLUGIN_LOGIN_URL, true);
    xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
    xmlHttpReq.setRequestHeader("Content-length", parameters.length);
    var outer = this;
    xmlHttpReq.onreadystatechange = function() {
      if (xmlHttpReq.readyState == 4) {
        outer._receiveMfSession(xmlHttpReq.responseText);
      }
    }
    xmlHttpReq.send(parameters);
  },
  
  _receiveMfSession: function(responseText) {
    if (responseText && responseText.match(this.RE_STRING_RESPONSE)) {
      var status = RegExp.$1.split(";");
      if (status[0] == "ok") {
        this._setMfSession(status[1]);
        this._postMfData(status[1]);
      } else if (status[0] == "unknownUser") {
        alert("Unknown User!");
      } else if (status[0] == "wrongPassword") {
        alert("Wrong Password!");
      } else {
        alert(responseText);
      }
    } else {
      alert(responseText);
    }
  },
  
  _postMfData: function(mfSession) {
    var selectedMicroFormats = new Array();
    var mfTree = document.getElementById("mfTree");
    var mfTreeRows = findElementNodes(mfTree, "treerow");
    for (var i = 0; i < mfTreeRows.length; i++) {
      var mfTreeCells = mfTreeRows[i].childNodes;
      if ((mfTreeCells != null) && (mfTreeCells.length > 2)) {
        var checkBoxValue = mfTreeCells[0].getAttribute("value");
        if (checkBoxValue == "true") {
          var type = mfTreeCells[2].getAttribute("label");
          if (type != null) {
            var matchResult = type.match(this.RE_MF_NODE); 
            if (matchResult != null) {
              var mfIndex = matchResult[1];
              if ((mfIndex >= 0) && (this.microFormats != null) && (mfIndex < this.microFormats.length)) {
                selectedMicroFormats.push(this.microFormats[mfIndex]);
              }
            }
          }
        }
      }
    }
    if (selectedMicroFormats.length > 0) {
      var microFormatContext = {};  
      var mfUrl = document.getElementById("mfUrl");
      microFormatContext["mfUrl"] = trim(mfUrl.value); 
      var mfTags = document.getElementById("mfTags");
      var tags = new Array();
      if (mfTags.value && (mfTags.value.length > 0)) {
        tags = mfTags.value.split(/\s*,\s*/);
      }        
      microFormatContext["mfTags"] = tags;
      microFormatContext["mfSelected"] = selectedMicroFormats;
      var parameters = "mfSessionId=" + mfSession + "&mfData=" + encodeURI(JSON.stringify(microFormatContext)).replace(/\&/g, "%26");
      // alert(parameters);
      var xmlHttpReq = new XMLHttpRequest();
      xmlHttpReq.open("POST", this.PLUGIN_REMEMBER_URL, true);
      xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
      xmlHttpReq.setRequestHeader("Content-length", parameters.length);
      var outer = this;
      xmlHttpReq.onreadystatechange = function() {
        if (xmlHttpReq.readyState == 4) {
          if (xmlHttpReq.responseText && xmlHttpReq.responseText.match(outer.RE_STRING_RESPONSE)) {
           if (RegExp.$1 == "ok") {
              alert("MicroFormats saved successfully.");
            } else if (RegExp.$1 == "invalidSession") {
              alert("Session invalid.");
              outer._setMfSession("");
              outer.onButtonRemember();
            } else if (RegExp.$1 == "missingParameters") {
              alert("Error on saving MicroFormats.");
            } else {
              alert(xmlHttpReq.responseText);
            }
          } else {
            alert(xmlHttpReq.responseText);
          }
        }
      }
      xmlHttpReq.send(parameters);
    }
  },
  
  _addMfTreeNodes: function() {
    
    var mfTree = document.getElementById("mfTree");
    if (mfTree && this.microFormats && (this.microFormats.length > 0)) {
      
      var level0ChildrenElement = document.createElement("treechildren");
  
      for (var i = 0; i < this.MF_TYPES.length; i++) {
        
        var mfType = this.MF_TYPES[i];
        var mfTypeNodeName = this.MF_TYPE_NODES[i];
        var mfTypeCount = 0; 
        for (var j = 0; j < this.microFormats.length; j++) {
          if (this.microFormats[j]["mfType"] == mfType) {
            mfTypeCount++;
          }
        }
        
        if (mfTypeCount > 0) {
        
          var level0ItemElement = document.createElement("treeitem");
          var level0ItemAttributeContainer = document.createAttribute("container");
          level0ItemAttributeContainer.nodeValue = "true";
          level0ItemElement.setAttributeNode(level0ItemAttributeContainer)
          var level0ItemAttributeOpen = document.createAttribute("open");
          level0ItemAttributeOpen.nodeValue = "true";
          level0ItemElement.setAttributeNode(level0ItemAttributeOpen)
          level0ChildrenElement.appendChild(level0ItemElement);
  
          var level0RowElement = document.createElement("treerow");
          level0ItemElement.appendChild(level0RowElement);
        
          var level0CheckboxElement = document.createElement("treecell");
          var level0CheckboxAttributeValue = document.createAttribute("value");
          level0CheckboxAttributeValue.nodeValue = "false";
          level0CheckboxElement.setAttributeNode(level0CheckboxAttributeValue);
          var level0CheckboxAttributeEditable = document.createAttribute("editable");
          level0CheckboxAttributeEditable.nodeValue = "true";
          level0CheckboxElement.setAttributeNode(level0CheckboxAttributeEditable);
          level0RowElement.appendChild(level0CheckboxElement);
  
          var level0PrimaryElement = document.createElement("treecell");
          var level0PrimaryAttributeLabel = document.createAttribute("label");
          level0PrimaryAttributeLabel.nodeValue = mfTypeNodeName + " [" + mfTypeCount + "]";
          level0PrimaryElement.setAttributeNode(level0PrimaryAttributeLabel);
          var level0PrimaryAttributeEditable = document.createAttribute("editable");
          level0PrimaryAttributeEditable.nodeValue = "false";
          level0PrimaryElement.setAttributeNode(level0PrimaryAttributeEditable);
          level0RowElement.appendChild(level0PrimaryElement);
        
          var level0TypeElement = document.createElement("treecell");
          var level0TypeAttributeLabel = document.createAttribute("label");
          level0TypeAttributeLabel.nodeValue = "mfType";
          level0TypeElement.setAttributeNode(level0TypeAttributeLabel);
          level0RowElement.appendChild(level0TypeElement);
          
          var level1ChildrenElement = document.createElement("treechildren");
          level0ItemElement.appendChild(level1ChildrenElement);
          
          this._addMfTypeSubTree(level1ChildrenElement, mfType);
          
        }
      }
      
      mfTree.appendChild(level0ChildrenElement);
    
    }
    
  },
  
  _addMfTypeSubTree: function(mfTreeTypeChildren, mfType) {
    
    if (mfTreeTypeChildren && mfType && this.microFormats && (this.microFormats.length > 0)) {
      
      for (var i = 0; i < this.microFormats.length; i++) {
        
        if (this.microFormats[i]["mfType"] == mfType) {

          var level1ItemElement = document.createElement("treeitem");
          mfTreeTypeChildren.appendChild(level1ItemElement);
          
          var level1RowElement = document.createElement("treerow");
          level1ItemElement.appendChild(level1RowElement);
          
          var level1CheckboxElement = document.createElement("treecell");
          var level1CheckboxAttributeValue = document.createAttribute("value");
          level1CheckboxAttributeValue.nodeValue = "true";
          level1CheckboxElement.setAttributeNode(level1CheckboxAttributeValue);
          var level1CheckboxAttributeEditable = document.createAttribute("editable");
          level1CheckboxAttributeEditable.nodeValue = "true";
          level1CheckboxElement.setAttributeNode(level1CheckboxAttributeEditable);
          level1RowElement.appendChild(level1CheckboxElement);
  
          var level1PrimaryElement = document.createElement("treecell");
          var level1PrimaryAttributeLabel = document.createAttribute("label");
          level1PrimaryAttributeLabel.nodeValue = this.microFormats[i]["mfName"];
          level1PrimaryElement.setAttributeNode(level1PrimaryAttributeLabel);
          var level1PrimaryAttributeEditable = document.createAttribute("editable");
          level1PrimaryAttributeEditable.nodeValue = "false";
          level1PrimaryElement.setAttributeNode(level1PrimaryAttributeEditable);
          level1RowElement.appendChild(level1PrimaryElement);
  
          var level1TypeElement = document.createElement("treecell");
          var level1TypeAttributeLabel = document.createAttribute("label");
          level1TypeAttributeLabel.nodeValue = "mfNode[" + i + "]";
          level1TypeElement.setAttributeNode(level1TypeAttributeLabel);
          level1RowElement.appendChild(level1TypeElement);
          
        }
        
      }
      
    }
    
  },
  
  _addMfPropertyTreeNodes: function(microFormat) {
    
    var mfPropertyTree = document.getElementById("mfPropertyTree");
    if (mfPropertyTree && this.microFormats && (this.microFormats.length > 0)) {
      
      var propertyDesc = microFormat['mfName'] + " [" + microFormat['mfType'] + "]";
      document.getElementById('mfPropertyDesc').innerHTML = propertyDesc;  
      
      var mfProperties = new Array();
      for (var property in microFormat) {
        if ((property != "mfName") && (property != "mfType")) {
          mfProperties.push(property);
        }
      }
      mfProperties.sort();
      
      var level0ChildrenElement = document.createElement("treechildren");

      for (var i = 0; i < mfProperties.length; i++) {
          
        var level0ItemElement = document.createElement("treeitem");
        level0ChildrenElement.appendChild(level0ItemElement);

        var level0RowElement = document.createElement("treerow");
        level0ItemElement.appendChild(level0RowElement);

        var level0PropertyElement = document.createElement("treecell");
        var level0PropertyAttributeLabel = document.createAttribute("label");
        level0PropertyAttributeLabel.nodeValue = mfProperties[i];
        level0PropertyElement.setAttributeNode(level0PropertyAttributeLabel);
        level0RowElement.appendChild(level0PropertyElement);
        
        var level0ValueElement = document.createElement("treecell");
        var level0ValueAttributeLabel = document.createAttribute("label");
        level0ValueAttributeLabel.nodeValue = microFormat[mfProperties[i]];
        level0ValueElement.setAttributeNode(level0ValueAttributeLabel);
        level0RowElement.appendChild(level0ValueElement);
        
      }
      
      mfPropertyTree.appendChild(level0ChildrenElement);
      
    }
  },
  
  _clearMfPropertyTree: function() {
    var mfPropertyTree = document.getElementById("mfPropertyTree");
    if (mfPropertyTree) {
      var treeChildNodes = mfPropertyTree.childNodes;
      for (var i = 0; i < treeChildNodes.length; i++) {
        if (treeChildNodes[i].nodeName == "treechildren") {
          mfPropertyTree.removeChild(treeChildNodes[i]);
        }
      }
    }
    document.getElementById('mfPropertyDesc').innerHTML = '';  
  }
  
}
